"""
基础路由模块
提供系统基础信息查询接口
"""

from typing import Dict, Any

from fastapi import APIRouter, HTTPException, Depends
from sqlalchemy.orm import Session

from AIAgents import AgentFactory
from config.database import get_db_session
from config.logging_config import get_logger
from emb.EmbFactory import EmbFactory
from llm.LLMFactory import LLMFactory
from pojo.ai_web_detail_tools_model import AIWebDetailToolsModel
from pojo.ai_web_mcp_tools_model import AIWebMCPToolsModel
from pojo.ai_web_tools_model import AIWebToolsModel
from constant.settings import settings
from config.redis_client import redis_client
import os
from datetime import datetime

logger = get_logger(__name__)

router = APIRouter()


@router.get("/health", summary="系统健康检查")
async def health_check(db: Session = Depends(get_db_session)) -> Dict[str, Any]:
    """
    系统健康检查端点
    检查数据库连接、Redis连接、关键服务状态等
    
    Returns:
        Dict[str, Any]: 健康检查结果
    """
    health_status = {
        "status": "healthy",
        "timestamp": str(datetime.now()),
        "version": settings.VERSION,
        "services": {}
    }
    
    try:
        # 检查数据库连接
        try:
            db.execute("SELECT 1")
            health_status["services"]["database"] = {
                "status": "healthy",
                "type": "mysql",
                "host": settings.MYSQL_HOST,
                "port": settings.MYSQL_PORT
            }
        except Exception as e:
            health_status["services"]["database"] = {
                "status": "unhealthy",
                "error": str(e),
                "type": "mysql"
            }
            health_status["status"] = "unhealthy"
        
        # 检查Redis连接
        try:
            if redis_client:
                await redis_client.ping()
                health_status["services"]["redis"] = {
                    "status": "healthy",
                    "type": "redis",
                    "host": settings.REDIS_HOST,
                    "port": settings.REDIS_PORT
                }
            else:
                health_status["services"]["redis"] = {
                    "status": "unhealthy",
                    "error": "Redis client not initialized"
                }
                health_status["status"] = "unhealthy"
        except Exception as e:
            health_status["services"]["redis"] = {
                "status": "unhealthy",
                "error": str(e),
                "type": "redis"
            }
            health_status["status"] = "unhealthy"
        
        # 检查ChromaDB
        try:
            from config.chromadb_config import chroma_db
            if chroma_db:
                collection_info = chroma_db.get_collection_info()
                health_status["services"]["chromadb"] = {
                    "status": "healthy",
                    "type": "chromadb",
                    "collection": settings.CHROMA_COLLECTION_NAME,
                    "documents": collection_info.get('count', 0)
                }
            else:
                health_status["services"]["chromadb"] = {
                    "status": "unhealthy",
                    "error": "ChromaDB not initialized"
                }
                health_status["status"] = "unhealthy"
        except Exception as e:
            health_status["services"]["chromadb"] = {
                "status": "unhealthy",
                "error": str(e),
                "type": "chromadb"
            }
            health_status["status"] = "unhealthy"
        
        # 检查AI服务配置
        ai_services = {}
        
        # OpenAI
        ai_services["openai"] = {
            "configured": bool(os.getenv("OPENAI_API_KEY")),
            "base_url": os.getenv("OPENAI_BASE_URL", "https://api.openai.com/v1")
        }
        
        # DashScope
        ai_services["dashscope"] = {
            "configured": bool(os.getenv("DASHSCOPE_API_KEY"))
        }
        
        # DeepSeek
        ai_services["deepseek"] = {
            "configured": bool(os.getenv("DEEPSEEK_API_KEY"))
        }
        
        # 智谱
        ai_services["zhipu"] = {
            "configured": bool(os.getenv("ZHIPU_API_KEY"))
        }
        
        # Mem0
        ai_services["mem0"] = {
            "configured": bool(os.getenv("MEM0_API_KEY"))
        }
        
        health_status["services"]["ai_services"] = ai_services
        
        # 检查MCP工具连接状态
        try:
            from mcp_tools.mcpManager import mcp_manager
            connected_servers = mcp_manager.get_connected_servers()
            health_status["services"]["mcp"] = {
                "status": "healthy",
                "connected_servers": len(connected_servers),
                "servers": connected_servers
            }
        except Exception as e:
            health_status["services"]["mcp"] = {
                "status": "unhealthy",
                "error": str(e)
            }
        
        # 基础统计信息
        try:
            tools_count = db.query(AIWebToolsModel).filter(
                AIWebToolsModel.is_enabled == 1
            ).count()
            
            mcp_tools_count = db.query(AIWebMCPToolsModel).filter(
                AIWebMCPToolsModel.status == 1
            ).count()
            
            health_status["statistics"] = {
                "enabled_tools": tools_count,
                "active_mcp_tools": mcp_tools_count,
                "available_llm_models": len(LLMFactory.list_models()),
                "available_embedding_models": len(EmbFactory.get_supported_models()),
                "available_agents": len(AgentFactory.get_available_agents())
            }
        except Exception as e:
            logger.warning(f"获取统计信息失败: {e}")
            health_status["statistics"] = {"error": str(e)}
        
        return health_status
        
    except Exception as e:
        logger.error(f"健康检查失败: {e}")
        return {
            "status": "unhealthy",
            "timestamp": str(datetime.now()),
            "error": str(e),
            "version": settings.VERSION
        }


@router.get("/models/llm", summary="获取支持的大语言模型列表")
async def get_llm_models() -> Dict[str, Any]:
    """
    获取支持的大语言模型列表
    
    Returns:
        Dict[str, Any]: 包含模型信息的字典
    """
    try:
        models = LLMFactory.list_models()
        return {
            "code": 200,
            "message": "获取成功",
            "data": {
                "models": models,
                "count": len(models)
            }
        }
    except Exception as e:
        logger.error(f"获取LLM模型列表失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取LLM模型列表失败: {str(e)}")


@router.get("/models/embedding", summary="获取支持的向量模型列表")
async def get_embedding_models() -> Dict[str, Any]:
    """
    获取支持的向量模型列表
    
    Returns:
        Dict[str, Any]: 包含模型信息的字典
    """
    try:
        models = EmbFactory.get_supported_models()
        return {
            "code": 200,
            "message": "获取成功",
            "data": {
                "models": models,
                "count": len(models)
            }
        }
    except Exception as e:
        logger.error(f"获取向量模型列表失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取向量模型列表失败: {str(e)}")


@router.get("/agents", summary="获取可用的智能体类型列表")
async def get_available_agents() -> Dict[str, Any]:
    """
    获取可用的智能体类型列表
    
    Returns:
        Dict[str, Any]: 包含智能体类型信息的字典
    """
    try:
        agents = AgentFactory.get_available_agents()
        return {
            "code": 200,
            "message": "获取成功",
            "data": {
                "agents": agents,
                "count": len(agents)
            }
        }
    except Exception as e:
        logger.error(f"获取智能体类型列表失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取智能体类型列表失败: {str(e)}")


@router.get("/tools", summary="获取可用的工具列表")
async def get_available_tools(db: Session = Depends(get_db_session)) -> Dict[str, Any]:
    """
    获取可用的工具列表
    
    Returns:
        Dict[str, Any]: 包含工具信息的字典
    """
    try:
        # 获取已启用的工具
        tools = db.query(AIWebToolsModel).filter(
            AIWebToolsModel.is_enabled == 1
        ).all()

        # 获取已启用的MCP工具
        mcp_tools = db.query(AIWebMCPToolsModel).filter(
            AIWebMCPToolsModel.status == 1
        ).all()

        # 获取已启用的详细工具
        detail_tools = db.query(AIWebDetailToolsModel).filter(
            AIWebDetailToolsModel.is_enabled == True
        ).all()

        tool_data = []
        for tool in tools:
            tool_dict = tool.to_dict()
            tool_data.append(tool_dict)

        mcp_tool_data = []
        for mcp_tool in mcp_tools:
            mcp_tool_dict = mcp_tool.to_dict()
            mcp_tool_data.append(mcp_tool_dict)

        detail_tool_data = []
        for detail_tool in detail_tools:
            detail_tool_dict = detail_tool.to_dict()
            detail_tool_data.append(detail_tool_dict)

        return {
            "code": 200,
            "message": "获取成功",
            "data": {
                "tools": tool_data,
                "mcp_tools": mcp_tool_data,
                "detail_tools": detail_tool_data,
                "tool_count": len(tool_data),
                "mcp_tool_count": len(mcp_tool_data),
                "detail_tool_count": len(detail_tool_data)
            }
        }
    except Exception as e:
        logger.error(f"获取工具列表失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取工具列表失败: {str(e)}")


@router.get("/tools/options", summary="获取工具集选项列表")
async def get_tools_options(db: Session = Depends(get_db_session)) -> Dict[str, Any]:
    """
    获取启用的工具集选项列表，用于下拉框选择
    
    Returns:
        Dict[str, Any]: 包含工具集选项信息的字典
    """
    try:
        # 查询启用的工具集
        tool_categories = db.query(AIWebToolsModel).filter(
            AIWebToolsModel.is_enabled == 1
        ).all()

        tools_options = []

        for category in tool_categories:
            # 获取该工具集下的工具数量统计
            tools_count = db.query(AIWebDetailToolsModel).filter(
                AIWebDetailToolsModel.parent_id == category.id,
                AIWebDetailToolsModel.tool_type == 1
            ).count()

            enabled_tools_count = db.query(AIWebDetailToolsModel).filter(
                AIWebDetailToolsModel.parent_id == category.id,
                AIWebDetailToolsModel.tool_type == 1,
                AIWebDetailToolsModel.is_enabled == True
            ).count()

            tools_options.append({
                "value": category.category_code,
                "label": f"{category.category_name} ({enabled_tools_count}/{tools_count}个工具)",
                "category_id": str(category.id),  # 转换为字符串格式
                "category_name": category.category_name,
                "category_code": category.category_code,
                "tool_type": 0,  # 工具集类型
                "description": category.description or '',
                "tools_count": tools_count,
                "enabled_tools_count": enabled_tools_count
            })

        return {
            "code": 200,
            "message": "获取成功",
            "data": {
                "tools": tools_options,
                "count": len(tools_options)
            }
        }

    except Exception as e:
        logger.error(f"获取工具集选项列表失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取工具集选项列表失败: {str(e)}")


@router.get("/mcp/options", summary="获取MCP工具选项列表")
async def get_mcp_options(db: Session = Depends(get_db_session)) -> Dict[str, Any]:
    """
    获取启用的MCP工具选项列表，用于下拉框选择
    
    Returns:
        Dict[str, Any]: 包含MCP工具选项信息的字典
    """
    try:
        # 查询已上线的MCP工具（status=1）
        mcp_tools = db.query(AIWebMCPToolsModel).filter(
            AIWebMCPToolsModel.status == 1
        ).all()

        mcp_options = []

        for mcp_tool in mcp_tools:
            # 获取该MCP工具下的详情工具数量
            tools_count = db.query(AIWebDetailToolsModel).filter(
                AIWebDetailToolsModel.parent_id == mcp_tool.id,
                AIWebDetailToolsModel.tool_type == 2
            ).count()

            enabled_tools_count = db.query(AIWebDetailToolsModel).filter(
                AIWebDetailToolsModel.parent_id == mcp_tool.id,
                AIWebDetailToolsModel.tool_type == 2,
                AIWebDetailToolsModel.is_enabled == True
            ).count()

            mcp_options.append({
                "value": str(mcp_tool.id),  # 转换为字符串格式
                "label": f"{mcp_tool.mcp_name} ({enabled_tools_count}/{tools_count}个工具)",
                "mcp_id": str(mcp_tool.id),  # 转换为字符串格式
                "mcp_name": mcp_tool.mcp_name,
                "description": mcp_tool.description or '',
                "status": mcp_tool.status,
                "status_display": mcp_tool.get_status_display(),
                "tools_count": tools_count,
                "enabled_tools_count": enabled_tools_count
            })

        return {
            "code": 200,
            "message": "获取成功",
            "data": {
                "mcp_tools": mcp_options,
                "count": len(mcp_options)
            }
        }

    except Exception as e:
        logger.error(f"获取MCP工具选项列表失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取MCP工具选项列表失败: {str(e)}")


@router.get("/tools/categories", summary="获取工具集选项列表")
async def get_tools_categories(db: Session = Depends(get_db_session)) -> Dict[str, Any]:
    """
    获取工具集选项列表，用于下拉框选择
    
    Returns:
        Dict[str, Any]: 包含工具集选项信息的字典
    """
    try:
        # 查询启用的工具集
        categories = db.query(AIWebToolsModel).filter(
            AIWebToolsModel.is_enabled == 1
        ).all()

        categories_options = []

        for category in categories:
            tools_count = len(category.get_tools_json())
            enabled_tools_count = len([
                tool for tool in category.get_tools_json()
                if tool.get('is_enabled', True)
            ])

            categories_options.append({
                "value": str(category.id),  # 转换为字符串格式
                "label": f"{category.category_name} ({enabled_tools_count}/{tools_count}个工具)",
                "category_id": str(category.id),  # 转换为字符串格式
                "category_name": category.category_name,
                "category_code": category.category_code,
                "description": category.description,
                "tools_count": tools_count,
                "enabled_tools_count": enabled_tools_count
            })

        return {
            "code": 200,
            "message": "获取成功",
            "data": {
                "categories": categories_options,
                "count": len(categories_options)
            }
        }

    except Exception as e:
        logger.error(f"获取工具集选项列表失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取工具集选项列表失败: {str(e)}")


@router.get("/models/all", summary="获取所有支持的模型列表")
async def get_all_models() -> Dict[str, Any]:
    """
    获取所有支持的模型列表
    
    Returns:
        Dict[str, Any]: 包含所有模型信息的字典
    """
    try:
        llm_models = LLMFactory.list_models()
        embedding_models = EmbFactory.get_supported_models()

        return {
            "code": 200,
            "message": "获取成功",
            "data": {
                "llm_models": llm_models,
                "embedding_models": embedding_models,
                "llm_count": len(llm_models),
                "embedding_count": len(embedding_models)
            }
        }
    except Exception as e:
        logger.error(f"获取模型列表失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取模型列表失败: {str(e)}")


@router.get("/system/info", summary="获取系统信息")
async def get_system_info(db: Session = Depends(get_db_session)) -> Dict[str, Any]:
    """
    获取系统信息，包括所有可用的组件类型
    
    Returns:
        Dict[str, Any]: 包含系统信息的字典
    """
    try:
        llm_models = LLMFactory.list_models()
        embedding_models = EmbFactory.get_supported_models()
        agents = AgentFactory.get_available_agents()

        # 获取工具统计
        tools_count = db.query(AIWebToolsModel).filter(
            AIWebToolsModel.is_enabled == 1
        ).count()

        return {
            "code": 200,
            "message": "获取成功",
            "data": {
                "llm_models": llm_models,
                "embedding_models": embedding_models,
                "agents": agents,
                "tools_count": tools_count,
                "llm_count": len(llm_models),
                "embedding_count": len(embedding_models),
                "agent_count": len(agents)
            }
        }
    except Exception as e:
        logger.error(f"获取系统信息失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取系统信息失败: {str(e)}")
